﻿/*
 * Catalyst - http://catalystobjects.com
 * 
 * New BSD License (BSD)
 * 
 * Copyright (c) 2009, Ashley Brener
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 * 
 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 * 
 * Neither the name of Midlet Earth nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using SubSonic;

namespace Catalyst
{
	public abstract class ValueTypeList<ItemType, ListType> : IList<ItemType>, IBusinessObjectList, IDataRelational
		where ListType : ValueTypeList<ItemType, ListType>, new()
	{
		/// <summary>
		/// The base static class that holds all schema info for the table.
		/// The class must be instanced at least once to populate this table.
		/// </summary>
		//protected static TableSchema.Table BaseSchema
		//{
		//    get
		//    {
		//        if (TempList.BaseSchema == null)
		//        {
		//            lock (_lockBaseSchema)
		//                if (table == null)
		//                    new ListType();
		//        }

		//        return TempList.BaseSchema;
		//    }
		//    set { TempList.BaseSchema = value; }
		//}

		private class IntermediaryList : BusinessObjectList<IntermediaryObject, IntermediaryList>
		{
			public IntermediaryList()
			{

			}

			public IntermediaryList(TableSchema.Table TableSchema)
			{
				BaseSchema = TableSchema;
			}

			//private TableSchema.Table table;

			public override TableSchema.Table GetTableSchema()
			{
				return BaseSchema;
			}
		}

		private class IntermediaryObject : BusinessObject<IntermediaryObject>
		{
			public override MappingList GetMappings()
			{
				throw new NotImplementedException();
			}

			public override TableSchema.Table GetTableSchema()
			{
				throw new NotImplementedException();
			}
		}

		private static string enumeratorColumnName;

		public virtual string GetEnumeratorColumnName()
		{
			return null;
		}

		private static TableSchema.Table table;

		protected internal TableSchema.Table BaseSchema
		{
			get 
			{
				if (table == null)
				{
					table = GetTableSchema();
				}

				return table;
			}
			set 
			{
				if (table == null)
				{
					table = value;
				}

				if (enumeratorColumnName == null)
				{
					enumeratorColumnName = GetEnumeratorColumnName();

					if (enumeratorColumnName == null)
					{
						if (table.TableType == TableType.Table)
						{
							if (table == GetTableSchema())
							{
								enumeratorColumnName = table.PrimaryKey.ColumnName;
							}
							else
							{
								foreach (TableSchema.ForeignKeyTable fkTable in table.ForeignKeys)
								{
									if (fkTable.TableName == GetTableSchema().TableName)
									{
										enumeratorColumnName = fkTable.ColumnName;

										break;
									}
								}
							}
						}
						else
						{
							enumeratorColumnName = table.Columns[0].ColumnName;
						}
					}
				}

				intermediaryList = new IntermediaryList(table);
			}
		}

		#region IDataRelational Members

		public abstract TableSchema.Table GetTableSchema();

		public void LoadAsRelation(TableSchema.Table RelatedTableSchema, string ForeignKeyName, object PrimaryKeyValue, HashSet<Aggregate> Aggregates)
		{
			BaseSchema = RelatedTableSchema;

			initialize();

			intermediaryList.LoadAsRelation<IDataRelational>(RelatedTableSchema, ForeignKeyName, PrimaryKeyValue, Aggregates);
		}

		public void LoadRelations(IList<string> RelationNames)
		{
			intermediaryList.LoadRelations(RelationNames);
		}

		#endregion

		#region IList<ItemType> Members

		public int IndexOf(ItemType item)
		{
			initialize();

			return items.IndexOf(item);
		}

		public void Insert(int index, ItemType item)
		{
			initialize();

			items.Insert(index, item);
		}

		public void RemoveAt(int index)
		{
			initialize();

			items.RemoveAt(index);
		}

		public ItemType this[int index]
		{
			get
			{
				initialize();

				return items[index];
			}
			set
			{
				initialize();

				items[index] = value;
			}
		}

		#endregion

		#region ICollection<ItemType> Members

		public void Add(ItemType item)
		{
			initialize();

			items.Add(item);
		}

		public void Clear()
		{
			initialize();

			items.Clear();
		}

		public bool Contains(ItemType item)
		{
			initialize();

			return items.Contains(item);
		}

		public void CopyTo(ItemType[] array, int arrayIndex)
		{
			initialize();

			items.CopyTo(array, arrayIndex);
		}

		public int Count
		{
			get
			{
				initialize();

				return items.Count;
			}
		}

		public bool IsReadOnly
		{
			get { return false; }
		}

		public bool Remove(ItemType item)
		{
			initialize();

			return items.Remove(item);
		}

		#endregion

		#region IEnumerable<ItemType> Members

		public IEnumerator<ItemType> GetEnumerator()
		{
			initialize();

			return items.GetEnumerator();
		}

		#endregion

		#region IEnumerable Members

		IEnumerator IEnumerable.GetEnumerator()
		{
			initialize();

			return items.GetEnumerator();
		}

		#endregion

		private void initialize()
		{
			if (items == null)
			{
				items = new List<ItemType>();
			}

			if (intermediaryList.Count > 0 && (items == null || intermediaryList.Count != items.Count))
			{
				items = new List<ItemType>();

				Tools tools = new Tools();

				string sVal = null;

				foreach (IntermediaryObject businessObject in intermediaryList)
				{
					sVal = businessObject.GetColumnValue<string>(enumeratorColumnName.ToLower());

					if (sVal == null)
					{
						sVal = string.Empty;
					}

					items.Add(tools.ConvertType<ItemType>(sVal));
				}
			}
		}
		
		private List<ItemType> items;

		private IntermediaryList intermediaryList;

		public void AddRange<T>(IEnumerable<T> collection) where T : ItemType
		{
			BaseSchema = GetTableSchema();

			initialize();

			items.AddRange(collection.Cast<ItemType>());
		}

		public void AddRange(IEnumerable<ItemType> collection)
		{
			BaseSchema = GetTableSchema();

			initialize();

			items.AddRange(collection);
		}

		public void Sort(IComparer<ItemType> comparer)
		{
			BaseSchema = GetTableSchema();

			initialize();

			items.Sort(comparer);
		}

		//private string enumeratorColumnName;

		//private void loadEnumeratorColumnName()
		//{
		//    if (enumeratorColumnName == null)
		//    {
		//        if (table != null)
		//        {
		//            if (table.TableType == TableType.Table)
		//            {
		//                if (table == GetTableSchema())
		//                {
		//                    enumeratorColumnName = table.PrimaryKey.ColumnName;
		//                }
		//                else
		//                {
		//                    foreach (TableSchema.ForeignKeyTable fkTable in table.ForeignKeys)
		//                    {
		//                        if (fkTable.TableName == GetTableSchema().TableName)
		//                        {
		//                            enumeratorColumnName = fkTable.ColumnName;

		//                            break;
		//                        }
		//                    }
		//                }
		//            }
		//            else
		//            {
		//                enumeratorColumnName = table.Columns[0].ColumnName;
		//            }
		//        }
		//    }
		//}

		//public override ListType Load(IDataReader Reader)
		//{
		//    return Load<ItemType>(Reader);
		//}

		public void Load(IDataReader Reader)
		{
			//TableSchema.Table tableSchema = GetTableSchema();

			//if (table != null && table != tableSchema)
			//{
			//    tableSchema = table;
			//}

			Load(BaseSchema, Reader);
			//return Load<T>(tableSchema, Reader);
		}

		public void Load(TableSchema.Table TableSchema, IDataReader Reader)
		{
			//loadSchema(TableName);

			BaseSchema = TableSchema;

			intermediaryList.Load(Reader);

			addItemsFromTempList();

			

			//try
			//{
			//    ItemType obj;

			//    //loadEnumeratorColumnName();

			//    while (Reader.Read())
			//    {
			//        obj = (ItemType)Enum.Parse(typeof(ItemType), Reader[enumeratorColumnName].ToString());

			//        Add(obj);
			//    }
			//}
			//finally
			//{
			//    if (Reader != null)
			//    {
			//        Reader.Close();
			//    }
			//}

			//return (ListType)this;
		}

		public void LoadAndCloseReader(TableSchema.Table TableSchema, IDataReader Reader)
		{
			BaseSchema = TableSchema;

			intermediaryList.LoadAndCloseReader(Reader);

			addItemsFromTempList();
		}


		//public override ListType Load(DataTable DataTable)
		//{
		//    return Load(GetTableSchema(), DataTable);
		//}

		public void Load(TableSchema.Table TableSchema, DataTable DataTable)
		{
			//loadSchema(TableName);

			BaseSchema = TableSchema;

			intermediaryList.Load(DataTable);

			addItemsFromTempList();

			//ItemType obj;

			//loadEnumeratorColumnName();
			
			//foreach (DataRow row in DataTable.Rows)
			//{
			//    obj = (ItemType)Enum.Parse(typeof(ItemType), row[enumeratorColumnName].ToString());

			//    Add(obj);
			//}
			
			//return (ListType)this;
		}

		public ListType LoadAll()
		{
			BaseSchema = GetTableSchema();

			intermediaryList.LoadAll();

			addItemsFromTempList();

			return (ListType)this;
		}

		private void addItemsFromTempList()
		{
			ItemType obj;
            
			foreach (IntermediaryObject item in intermediaryList)
			{
				obj = (ItemType)Enum.Parse(typeof (ItemType), item.GetColumnValue<string>(enumeratorColumnName.ToLower()));

				Add(obj);
			}
		}

		#region IAbstractList Members

		public void Load(DataTable dataTable)
		{
			Load(BaseSchema, dataTable);
		}

		public void LoadAndCloseReader(IDataReader dataReader)
		{
			LoadAndCloseReader(BaseSchema, dataReader);
		}



		public string ProviderName
		{
			get
			{
				return BaseSchema.Provider.Name;
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		public void Sort(string columnName, bool ascending)
		{
			throw new NotImplementedException();
		}

		public DataTable ToDataTable()
		{
			throw new NotImplementedException();
		}

		#endregion

		#region IBusinessObjectList Members


		public void Save()
		{
			throw new NotImplementedException();
		}

		public void Save(int userID)
		{
			throw new NotImplementedException();
		}

		public void Save(Guid userID)
		{
			throw new NotImplementedException();
		}

		public void Save(string userName)
		{
			throw new NotImplementedException();
		}

		#endregion
	}
}
